package com.franklin.ideaplugin.easytesting.ui;

import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import lombok.Getter;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author Ye Junhui
 * @since 2023/6/2
 */
@Getter
public class HttpHeaderCellRenderer implements TableCellRenderer {

    private final boolean selected;
    private final JTable jTable;
    private JBCheckBox checkBox;

    public HttpHeaderCellRenderer(boolean selected, JTable jTable) {
        this.selected = selected;
        this.checkBox = new JBCheckBox("Select All", selected);
        this.jTable = jTable;
        JTableHeader tableHeader = jTable.getTableHeader();
        checkBox.setForeground(tableHeader.getForeground());
        checkBox.setBackground(tableHeader.getBackground());
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
        checkBox.setFont(tableHeader.getFont());

        tableHeader.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectColumn = tableHeader.columnAtPoint(e.getPoint());
                if (selectColumn != 0) {
                    return;
                }
                boolean isSelectAll = !checkBox.isSelected();
                checkBox.setSelected(isSelectAll);
                HttpHeaderTableModel httpHeaderTableModel = (HttpHeaderTableModel) jTable.getModel();
                for (int i = 0; i < httpHeaderTableModel.getRowCount(); i++) {
                    httpHeaderTableModel.setValueAt(isSelectAll, i, 0);
                }
                jTable.repaint();
            }
        });

    }


    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (row > 0 || column > 0) {
            return new JBLabel(value.toString());
        }
        //表头
        return this.checkBox;
    }
}
